<?php
/**
 * Memcache缓存
 * 配置示例：
	 $_options = array(
		'servers' => array(
			array(
				'host' => '127.0.0.1',
				'port' => '11211',
				'persistent' => true,
				'weight' => 1,
				'timeout' => 1,
				'retry_interval' => 15,
				'status' => true,
				'failure_callback' => false,
			),
		),
		'timeout' => 1200,
		'compression' => false
	 );
 * 
 * @package SFramework
 * @subpackage Cache
 * @author Shuky
 * @since v1.0
 * @version $Id: Memcache.php 97 2011-01-22 16:59:07Z shukyoo@gmail.com $
 */
namespace SF\Cache;

class Memcache extends CacheAbstract implements CacheInterface
{
    const DEFAULT_HOST = '127.0.0.1';
    const DEFAULT_PORT =  11211;
    const DEFAULT_PERSISTENT = true;
    const DEFAULT_WEIGHT  = 1;
    const DEFAULT_TIMEOUT = 1;
    const DEFAULT_RETRY_INTERVAL = 15;
    const DEFAULT_STATUS = true;
    const DEFAULT_FAILURE_CALLBACK = null;

	protected $_mc = null;

	protected $_expire = 1200;


	public function __construct(array $options = array())
	{
		if (!extension_loaded('memcache')) {
			throw new CacheException('Memcache不存在');
		}
		parent::__construct($options);
		$this->_mc = new \Memcache;
		if (!empty($this->_options['expire'])) {
			$this->_expire = $this->_options['expire'];
		}
		if (isset($this->_options['servers'])) {
			foreach ($this->_options['servers'] as $server) {
				isset($server['host']) || $server['host'] = self::DEFAULT_HOST;
				isset($server['port']) || $server['port'] = self::DEFAULT_PORT;
				isset($server['persistent']) || $server['persistent'] = self::DEFAULT_PERSISTENT;
				isset($server['weight']) || $server['weight'] = self::DEFAULT_WEIGHT;
				isset($server['timeout']) || $server['timeout'] = self::DEFAULT_TIMEOUT;
				isset($server['retry_interval']) || $server['retry_interval'] = self::DEFAULT_RETRY_INTERVAL;
				isset($server['status']) || $server['status'] = self::DEFAULT_STATUS;
				isset($server['failure_callback']) || $server['failure_callback'] = self::DEFAULT_FAILURE_CALLBACK;
				$this->_mc->addServer($server['host'], $server['port'], 
													$server['persistent'], $server['weight'], $server['timeout'], 
													$server['retry_interval'], $server['status'], $server['failure_callback']);
			}
		}
	}


	public function get($key)
	{
		return $this->_mc->get($key);
	}


	public function set($key, $value, $expire = null)
	{
		$flag = (isset($this->_options['compression']) && $this->_options['compression'] == true) ? MEMCACHE_COMPRESSED : 0;
		$expire = ($expire == null) ? $this->_expire : $expire;
		$this->_mc->set($key, $value, $flag, $expire);
	}


	public function del($key)
	{
		$this->_mc->delete($key);
	}
}